package org.opens.guava.utilites.eventBus.myeventbus;

import java.util.concurrent.Executor;

public class MyEventBus implements MyBus {

    private final MyRegistryTable table = new MyRegistryTable();

    private final static String DEFAULT_TOPIC = "default topic";

    private final MyEventExceptionHandle exceptionHandle;

    private String busName;

    private final MyDispatcher dispatcher;

    private final static String DEAFULT_BUS_NAME = "default";

    public MyEventBus() {
        this(null, DEAFULT_BUS_NAME, MyDispatcher.SEQ_EXECUTOR_SERVICE);
    }

    public MyEventBus(String busName) {
        this(null, busName, MyDispatcher.SEQ_EXECUTOR_SERVICE);
    }

    public MyEventBus(MyEventExceptionHandle exceptionHandle) {
        this(exceptionHandle, DEAFULT_BUS_NAME, MyDispatcher.SEQ_EXECUTOR_SERVICE);
    }

    public MyEventBus(MyEventExceptionHandle exceptionHandle, String busName, Executor executor) {
        this.exceptionHandle = exceptionHandle;
        this.busName = busName;
        this.dispatcher = MyDispatcher.newDispatcher(exceptionHandle, executor);
    }

    @Override
    public void register(Object subscriber) {
        this.table.bind(subscriber);
    }

    @Override
    public void unregister(Object subscriber) {
        this.table.unbind(subscriber);
    }

    @Override
    public void post(Object event) {
        this.post(event, DEFAULT_TOPIC);
    }

    @Override
    public void post(Object event, String topic) {
        dispatcher.dispatch(this, table, event, topic);
    }

    @Override
    public void close() {

    }

    @Override
    public String getBusName() {
        return this.busName;
    }

}
